"""
@release: fsray-api-alpha
@file: Task.py
@author: lingdubing
@desc: 电动车任务类
@character: utf-8
"""

import ast
from datetime import datetime
from celery import Celery
from config import settings
from models.models import Machine, Record, Area, User
from schemas.response import *
from core.Utils import generate_uuid, is_machine_in_area
import time
from service.MachineService import MachineService
from service.UserService import UserService
from service.AreaService import AreaService
from service.RecordService import RecordService

celery_app = settings.CELERY_APP


@celery_app.task
def simulate_ev_ride(machine_id: str, user_id: str, route):
    """
    模拟电动车骑行的任务，更新电动车的位置。
    """
    machine_service = MachineService()
    user_service = UserService()
    area_service = AreaService()
    record_service = RecordService()

    # 生成当前时间
    start_time = datetime.utcnow()
    tracejectory = []

    print(f"电动车 {machine_id} 的骑行任务开始，用户 {user_id} 从起点出发。")

    # 模拟骑行过程
    for i in route:
        # 每30秒更新一次位置信息
        time.sleep(30)
        longitude, latitude = map(float, i.split(","))
        machine_info = machine_service.get_machine_by_id(machine_id)
        machine_info.machine_point = {
            "longitude": longitude,
            "latitude": latitude
        }
        machine_service.create(machine_info)

        tracejectory.append((longitude, latitude))

    # 更改用户状态
    user_info = user_service.get_user_by_id(user_id)
    user_info.user_status = 2
    user_service.create(user_info)

    # 骑行结束，更新电池信息
    machine_info = machine_service.get_machine_by_id(machine_id)
    machine_info.machine_battery -= len(tracejectory) * 1
    machine_info.update_time = datetime.utcnow()
    # 查看所有不为异常区域的区域信息
    area_info_list = []
    result = area_service.get_all_area()
    for val in result:
        area_info = {
            "area_id": val.area_id,
            "area_desc": ast.literal_eval(val.area_desc)
        }
        area_info_list.append(area_info)

    # 判断电动车是否在合法区域内
    destination_point = {
        "longitude": route[-1].split(",")[0],
        "latitude": route[-1].split(",")[1]
    }
    area_id = is_machine_in_area(destination_point, area_info_list)
    if area_id == 0:
        machine_info.status = 2
        machine_info.area_id = area_id
    else:
        machine_info.status = 1
        machine_info.area_id = area_id

    machine_service.create(machine_info)

    # 生成结束时间
    end_time = datetime.utcnow()

    # 创建骑行记录
    record = Record(machine_id=machine_id,
                    user_id=user_id, start_time=start_time,
                    end_time=end_time, tracejectory=tracejectory, stop_time=0,
                    consume_battery=len(tracejectory) * 1,
                    record_id=generate_uuid(), update_by = user_id, create_by = user_id)
    record_service.create(record)

    print( f"骑行结束，电动车 {machine_id} 最终位置：({destination_point['longitude']}, {destination_point['latitude']})，电池剩余：{machine_info.machine_battery}%")
